package com.taxigang.server;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import com.allen_sauer.gwt.log.client.Log;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;
import com.taxigang.client.LoginService;
import com.taxigang.shared.LoginInfo;

public class LoginServiceImpl extends RemoteServiceServlet implements
	LoginService {

	enum ProviderEnum{ Google, Yahoo};


	public LoginInfo login(String requestUri) {
		
		Log.info("LoginServiceImpl:login:"+requestUri);
		/**/
	    Map<ProviderEnum,String> authDomainMap = new HashMap<ProviderEnum,String>();
	    authDomainMap.put(ProviderEnum.Google, "google.com");
	    authDomainMap.put(ProviderEnum.Yahoo, "yahoo.com");

	    Set attributesRequest = new HashSet();
	    attributesRequest.add("openid.mode=checkid_immediate");
	    attributesRequest.add("openid.ns=http://specs.openid.net/auth/2.0");
	    attributesRequest.add("openid.return_to=http://taxigangx.appspot.com"); 
	    
	    Map<ProviderEnum,String> federatedIdentityMap = new HashMap<ProviderEnum,String>();
	    federatedIdentityMap.put(ProviderEnum.Google, "https://www.google.com/accounts/o8/id");
	    federatedIdentityMap.put(ProviderEnum.Yahoo, "http://open.login.yahooapis.com/openid20/www.yahoo.com/xrds");
	    
		ProviderEnum provider = ProviderEnum.Google;

	    /**/

		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		LoginInfo loginInfo = new LoginInfo();

		if (user != null) {
			loginInfo.setId(user.getUserId());
			
			loginInfo.setLoggedIn(true);
			loginInfo.setEmailAddress(user.getEmail());
			loginInfo.setNickname(user.getNickname());
			loginInfo.setLogoutUrl(userService.createLogoutURL(requestUri));
			loginInfo.setLoginProvider(provider.toString());
			
			//String logoutURL = userService.createLogoutURL(requestUri, authDomainMap.get(provider));
			//loginInfo.setLogoutUrl(logoutURL);

			
		} else {
			loginInfo.setLoggedIn(false);
			loginInfo.setLoginUrl(userService.createLoginURL(requestUri));
			loginInfo.setLogoutUrl(userService.createLogoutURL(requestUri));
			Log.info("login service:logged out:"+loginInfo.getLoginUrl());
			
			//String loginURL = userService.createLoginURL(requestUri, authDomainMap.get(provider), federatedIdentityMap.get(provider), attributesRequest);
			//loginInfo.setLoginUrl(loginURL);

		}
		return loginInfo;
	}


}
